import { getChildrenUser, getNode, getToken } from '@/api/user'
import { resetRouter } from '@/router'
import { removeToken, setToken } from '@/utils/auth'
import { Message } from 'element-ui'

const getDefaultState = () => {
  return {
    token: '',
    node: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER: (state, user) => {
    state.userInfo = user
  },
  SET_NODE: (state, node) => {
    state.node = node
  },
  SET_CHILDREN_USER: (state, children) => {
    state.ChildrenUsers = children
  }
}

const actions = {
  // user login 主用户基本信息
  async login({ commit }, userInfo) {
    // const { User, Password } = userInfo
    console.log(userInfo)
    // debugger
    const res = await getToken(userInfo)
    console.log(res)
    // debugger
    if (res.Result) {
      setToken({
        token: res.Token,
        Expired: res.Expired
      })
      commit('SET_USER', userInfo)
      commit('SET_TOKEN', res.Token)
      return true
    } else {
      return false
    }

  },
  // 获取用户节点信息
  async setNode({ commit, state }) {
    const User = state.userInfo
    const params = {
      'Token': state.token,
      'User': User.userInfo.User
    }
    const res = await getNode(params)
    if (res.Result) {
      commit('SET_NODE', res.data)
      console.log(res)
      return res.data
    }
    return res
  },

  // 退出登陆
  async logout({ commit, state }) {
    await removeToken() // must remove  token  first
    commit('RESET_STATE')
    // 断开sockets
    resetRouter()

  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  async setChildrenUsers({ commit, state }) {
    if (!state.User) return Message('请重新登陆')
    const params = {
      Token: state.token,
      User: state.userInfo.User
    }
    const res = await getChildrenUser(params)
    console.log(res)
    if (res.Result) {
      commit('SET_CHILDREN_USER', res.data)
    }
  }
//
}

export default
{
  namespaced: true,
  state,
  mutations,
  actions
}

